package GearCommands;

import Connections.Peer;
import Gear.Factory;
import Gear.Gear;

import java.io.File;
import java.lang.reflect.Array;
import java.nio.file.FileSystems;
import java.util.Scanner;

/**
 * Implementation of the user command edit.
 * Gives write permission to a file temporarily.
 *
 * @author Rodrigo Martins Racanicci
 */
public class GearCommandEdit implements GearCommand {

    @Override
    public void execute(String[] args, Gear gear) {
        try {
            if (args.length < 2) throw new IllegalArgumentException("Too few arguments to edit command.");

            File f = FileSystems.getDefault().getPath(Factory.getInstance().getSettings().getGearPath().toString(), (String) Array.get(args, 1)).toFile();

            Factory.getInstance().getLocalFileMutex().acquire(args[1]);
            if (Peer.getInstance().lockFile(args[1])) {
                System.out.println("Now you can edit the resquest file\nPress ENTER when done!");
                f.setWritable(true);
                new Scanner(System.in).nextLine();

                if (Peer.getInstance().unlockFile(args[1])) {
                    f.setReadOnly();
                    System.out.println("File readyonly again!");
                } else {
                    System.out.println("Error on unlock file!");
                }
            } else {
                System.out.println("Unable to edit file: file are being used by another peer, or the file doesn't exist!");
            }
            Factory.getInstance().getLocalFileMutex().release(args[1]);
        } catch (IllegalArgumentException ex) {
            System.out.println(ex.getMessage());
        }
    }
}
